from __future__ import division
import cv2
import numpy as np


cap = cv2.VideoCapture(0)


def nothing(*arg):
    pass


icol = (36, 202, 59, 71, 255, 255)
cv2.namedWindow('colortest')
cv2.createTrackbar('lowHue', 'colortest', icol[0], 255, nothing)
cv2.createTrackbar('lowSat', 'colortest', icol[1], 255, nothing)
cv2.createTrackbar('lowVal', 'colortest', icol[2], 255, nothing)

cv2.createTrackbar('highHue', 'colortest', icol[3], 255, nothing)
cv2.createTrackbar('highSat', 'colortest', icol[4], 255, nothing)
cv2.createTrackbar('highVal', 'colortest', icol[5], 255, nothing)

frame = cv2.imread('l3.png')

while True:
    ret, frame = cap.read()
    cv2.imshow("capture", frame)
    if cv2.waitKey(1) & 0xFF == ord('o'):
        break
    lowHue = cv2.getTrackbarPos('lowHue', 'colortest')
    lowSat = cv2.getTrackbarPos('lowSat', 'colortest')
    lowVal = cv2.getTrackbarPos('lowVal', 'colortest')
    highHue = cv2.getTrackbarPos('highHue', 'colortest')
    highSat = cv2.getTrackbarPos('highSat', 'colortest')
    highVal = cv2.getTrackbarPos('highVal', 'colortest')

    cv2.imshow('frame', frame)
    frameBGR = cv2.GaussianBlur(frame, (7, 7), 0)
    cv2.imshow('blurred', frameBGR)
    hsv = cv2.cvtColor(frameBGR, cv2.COLOR_BGR2HSV)
    colorLow = np.array([lowHue, lowSat, lowVal])
    colorHigh = np.array([highHue, highSat, highVal])
    mask = cv2.inRange(hsv, colorLow, colorHigh)

    kernal = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernal)
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernal)

    cv2.imshow('mask', mask)

    result = cv2.bitwise_and(frame, frame, mask=mask)

    cv2.imshow('colorTest', result)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()